package com.apes.util;

import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.fileserver.domain.File;
import com.apes.framework.plugin.fileserver.service.FileService;
import com.apes.framework.util.MD5Util;
import com.apes.framework.util.MapUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 类描述：照片工具类
 *
 * @ClassName ImageUtil
 * @Description 描述
 * @Author wushilong
 * @Date 2023/3/31 17:22
 * @Version 1.0
 */
@Service
public class ImageUtilService {

    /**
     *
     * @param imgUrl 图片URL
     * @param id 订单id
     * @param relatedNumber 固定值
     * @param index 结束下标(没有结束下标可填-1)
     * @return
     */
    public List storeImg(String imgUrl, String id, String relatedNumber, int index){
        List list = new ArrayList();
        try {
            // 根据图片连接获取 文件名 以及 文件类型
            String fileName;
            String contentType;
            if (index != -1){
                fileName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1, index);
                contentType = "image/" + imgUrl.substring(imgUrl.lastIndexOf(".") + 1, index);
            }else {
                fileName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
                contentType = "image/" + imgUrl.substring(imgUrl.lastIndexOf(".") + 1);
            }

            // 获取图片转换为 byte
            URL url = new URL(imgUrl);
            byte[] data = IOUtils.toByteArray(url);

            //构造自定义文件类型
            File f = new File(fileName, contentType, data.length, data);
            f.setMd5(MD5Util.encrypt(fileName + id + relatedNumber));
            File returnFile = SpringManager.getBean(FileService.class).saveFile(f);
            list.add(MapUtil.mapper("id", returnFile.getId(),
                    "type", returnFile.getContentType(),
                    "size", returnFile.getSize(),
                    "name", returnFile.getName(),
                    "fileName", returnFile.getName()));
        } catch (Exception e) {
            return null;
        }
        return list;
    }
}
